package jsyf.oa.service.report.mineCustomer;


import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.report.intentCustomer.ReportCustomerDao;
import jsyf.oa.dao.report.mineCustomer.CustomerReportDao;
import jsyf.oa.entity.report.mineCustomer.CustomerReportEntity;
import jsyf.oa.facade.report.mineCustomer.CustomerReportFacade;
import jsyf.oa.service.report.reportCommon.ReportCommonMethodsAndConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by 92852 on 2018/4/5.
 * 吴江华
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class CustomerReportService implements CustomerReportFacade {
    @Autowired
    private CustomerReportDao customerReportDao;
    @Autowired
    private ReportCustomerDao reportCustomerDao;
    @Autowired
    private ReportCommonMethodsAndConstant common;

    /*个人*/
    @Override
    public JSONObject getForPersonalCustomerList(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        //用户ID
        String userId = jsonParams.getString("userId");
        //时间
        String dateTime = jsonParams.getString("dateTime");
        //模糊查询
        String key = jsonParams.getString("key");
        /*分页信息*/
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        StringBuffer condition = new StringBuffer();
        if (jsonParams.containsKey("pageSize")) {
            pageSize = jsonParams.getInteger("pageSize");
        }
        if (jsonParams.containsKey("requestPage")) {
            requestPage = jsonParams.getInteger("requestPage");
        }
        if (!StringUtils.isBlank(userId)) {
            condition.append(" AND CREATE_USER_ID=" + "'" + userId + "'");
        }
        if (!StringUtils.isBlank(dateTime)) {
            condition.append(" AND CREATE_TIME LIKE" + "'" + dateTime + "%'" + "\n");
        }
        if (!StringUtils.isBlank(key)) {
            condition.append(" AND (`NAME` LIKE" + "'%" + key + "%'" + "OR(TEL LIKE" + "'%" + key + "%'" + "))" + "\n");
        }
        List<JSONObject> records = customerReportDao.getForPersonalCustomerList(condition.toString(), requestPage, pageSize);
        int recordCount = customerReportDao.getCountPersonalCustomerList(userId, dateTime, key);
        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;
        //存放分页信息
        JSONObject sendData = new JSONObject();
        //存放list
        JSONObject result = new JSONObject();
        sendData.put("recordCount", recordCount);
        sendData.put("pageCount", pageCount);
        sendData.put("requestPage", 1);
        result.put("pager", sendData);
        // 子数组对象
        result.put("records", records);
        return result;
    }

    /*部门*/
    @Override
    public JSONObject getForDepartCustomerList(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        //用户ID
        String userId = jsonParams.getString("userId");
        //时间
        String dateTime = jsonParams.getString("dateTime");
        List<JSONObject> records = customerReportDao.getForPersonalCustomerList(userId, dateTime);
        JSONObject obj = new JSONObject();
        obj.put("records", records);
        return obj;
    }

    /*公司*/
    @Override
    public JSONObject getForCompanyCustomerList(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        //用户ID
        String userId = jsonParams.getString("userId");
        //时间
        String dateTime = jsonParams.getString("dateTime");
        List<JSONObject> records = customerReportDao.getForCompanyCustomerList(userId, dateTime);
        JSONObject obj = new JSONObject();
        obj.put("records", records);
        return obj;
    }

    /*集团*/
    @Override
    public JSONObject getForGroupCustomerList(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        //用户ID
        String userId = jsonParams.getString("userId");
        //时间
        String dateTime = jsonParams.getString("dateTime");

      /*获取用户manageFlag*/
        int manageFlag = customerReportDao.getManageFlagByUserId(userId);
        String sql = "";
        if (manageFlag == 1) {
        /*获得集团下的公司ID（后台）*/
            sql = common.getAllCompanysIdByUserId(userId);
        } else {
            /*获得集团下的公司ID（有兼职总经理）*/
            sql = common.getAllCompanysIdByUserIdPart(userId);
        }
        List<JSONObject> records = customerReportDao.getForGroupCustomerList(userId, dateTime, sql);
        JSONObject obj = new JSONObject();
        obj.put("records", records);
        return obj;
    }

    /*查询所有*/
    @Override
    public JSONObject getAllCustomerList(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String key = jsonParams.getString("key");
        //分页信息
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (jsonParams.containsKey("pageSize")) {
            pageSize = jsonParams.getInteger("pageSize");
        }
        if (jsonParams.containsKey("requestPage")) {
            requestPage = jsonParams.getInteger("requestPage");
        }
            /*获取身份标志*/
        JSONObject roleFlag = customerReportDao.getManageFlagAndFrontFlagAndAreaTypeByUserId(userId);
          /*获取集团人员可以看到的公司*/
        String companyId = common.getAllCompanysIdByUserId(userId);
        /*获取所有客户*/
        List<JSONObject> records = customerReportDao.getAllCustomerList(userId, key, companyId, requestPage, pageSize, roleFlag);
        /*获得查询数目*/
        int recordCount = customerReportDao.getCountByCompanyIdAndUserIdAndKey(companyId, userId, key, roleFlag);
        //分装前端需要的格式
        int pageCount = 0;
        if (recordCount < pageSize) {
            pageCount = 1;
        } else {
            double flag = Math.ceil(recordCount / pageSize + 1);
            pageCount = ((int) flag);
        }
        if (recordCount == 0) {
            pageCount = 0;
        }
        //存放分页信息
        JSONObject sendData = new JSONObject();
        //存放list
        JSONObject result = new JSONObject();
        sendData.put("recordCount", recordCount);
        sendData.put("pageCount", pageCount);
        sendData.put("requestPage", 1);
        result.put("pager", sendData);
        // 子数组对象
        result.put("records", records);
        return result;

    }

    /*根据companyId获取所有客户*/
    @Override
    public JSONObject getAllCustomerListByCompanyId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String companyId = jsonParams.getString("companyId");
        String key = jsonParams.getString("key");
        //分页信息
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (jsonParams.containsKey("pageSize")) {
            pageSize = jsonParams.getInteger("pageSize");
        }
        if (jsonParams.containsKey("requestPage")) {
            requestPage = jsonParams.getInteger("requestPage");
        }
        List<JSONObject> records = customerReportDao.getAllCustomerListByCompanyId(companyId, key, requestPage, pageSize);
        int recordCount = customerReportDao.getCountCustomerListByCompanyId(companyId, key);
        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;
        //存放分页信息
        JSONObject sendData = new JSONObject();
        //存放list
        JSONObject result = new JSONObject();
        sendData.put("recordCount", recordCount);
        sendData.put("pageCount", pageCount);
        sendData.put("requestPage", 1);
        result.put("pager", sendData);
        // 子数组对象
        result.put("records", records);
        return result;
    }

    /*集团到部门*/
    @Override
    public JSONObject getDepartByCompanyId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        //公司ID
        String companyId = jsonParams.getString("companyId");
        //时间
        String dateTime = jsonParams.getString("dateTime");
        List<JSONObject> records = customerReportDao.getDepartByCompanyId(companyId, dateTime);
        JSONObject obj = new JSONObject();
        obj.put("records", records);
        return obj;
    }

    /*根据客户ID获得客户详细信息*/
    @Override
    public JSONObject getCustomerById(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String customerId = jsonParams.getString("customerId");
        JSONObject customerInfo = customerReportDao.getCustomerById(customerId);
        List<JSONObject> customerVisitInfo = customerReportDao.getVisitCustomerInfoByCustomerId(customerId);
        JSONObject result = new JSONObject();
        result.put("customerInfo", customerInfo);
        result.put("customerVisitInfo", customerVisitInfo);
        return result;
    }

    @Override
    public JSONObject saveIntentCustomerInfo(String jsonData) {
        CustomerReportEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), CustomerReportEntity.class);
        Integer rows = 0;
        JSONObject obj = new JSONObject();
        if (entity.getIntentionModel() != null) {
            entity.setIntentionModel(entity.getIntentionModel().toUpperCase());
        }
        if (org.apache.commons.lang3.StringUtils.isBlank(entity.getId()) || "0".equals(entity.getId())) {
            if (!(org.apache.commons.lang3.StringUtils.isBlank(entity.getBuyDate()) && org.apache.commons.lang3.StringUtils.isBlank(entity.getBuyType()))) {
                entity.setIntentionTime(customerReportDao.getCurrentTime());
            }
            String tel = entity.getTel();
            if (org.apache.commons.lang3.StringUtils.isBlank(reportCustomerDao.getForTel(tel))) {
                rows = customerReportDao.add(entity);
                if (rows > 0) {
                    obj.put("records", "保存成功");
                } else {
                    obj.put("records", "保存失败");
                }
            } else {
                obj.put("records", "电话号码已存在");
            }

        } else {
            if (!(org.apache.commons.lang3.StringUtils.isBlank(entity.getBuyDate()) && org.apache.commons.lang3.StringUtils.isBlank(entity.getBuyType()))) {
                entity.setIntentionTime(customerReportDao.getCurrentTime());
            }
            rows = customerReportDao.update(entity);
            if (rows > 0) {
                obj.put("records", "保存成功");
            } else {
                obj.put("records", "保存失败");
            }
        }
        return obj;
    }
}
